package p.ithorns.framework.redis.stream;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.stream.RecordId;
import org.springframework.data.redis.connection.stream.StreamRecords;
import org.springframework.data.redis.connection.stream.StringRecord;
import org.springframework.data.redis.core.StreamOperations;

import java.util.Collections;

/**
 * @Author: liuhaitao
 * @Date: 2022/12/9 14:53
 * @Description:
 */
public class RedisStreamProducer {

    private final static Logger log = LoggerFactory.getLogger(RedisStreamProducer.class);
    private final RedisStreamTemplate streamTemplate;
    private final StreamOperations streamOps;

    public RedisStreamProducer(RedisStreamTemplate streamTemplate) {
        this.streamTemplate = streamTemplate;
        this.streamOps = streamTemplate.getStreamOps();
    }

    public <T> String objRecord(String streamKey, T obj) {
        RecordId recordId = streamOps
                .add(StreamRecords.objectBacked(obj).withStreamKey(streamKey));

        // log.info("返回的record-id:[{}]", recordId);
        return recordId.getValue();
    }

    public String stringRecord(String streamKey, String value) {
        StringRecord record = StreamRecords.string(Collections.singletonMap("name", value)).withStreamKey(streamKey);
        RecordId recordId = streamOps.add(record);
        log.info("返回的record-id:[{}]", recordId);
        return recordId.getValue();
    }

}